package com.ruoyi.factory.manpower.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.manpower.domain.OverTimePer;
import com.ruoyi.factory.manpower.mapper.OverTimeMapper;
import com.ruoyi.factory.manpower.service.OverTimeService;
import com.ruoyi.factory.manpower.utils.SignHelper;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import nccloud.open.api.auto.token.factory.APIUtilsFactory;
import nccloud.open.api.auto.token.factory.NCCVersionEnum;
import nccloud.open.api.auto.token.itf.IAPIUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OverTimeServiceImpl implements OverTimeService {

    protected final Logger logger = LoggerFactory.getLogger(OverTimeServiceImpl.class);

    @Autowired
    public OverTimeMapper overTimeMapper;

    @Value("${erp.openapi.ip}")
    private String pip;
    @Value("${erp.openapi.port}")
    private String pport;
    @Value("${erp.openapi.busi_center}")
    private String pbusi_center;
    @Value("${erp.openapi.app_id}")
    private String papp_id;
    @Value("${erp.openapi.app_secret}")
    private String papp_secret;
    @Value("${erp.openapi.public_key}")
    private String ppublic_key;
    @Value("${erp.openapi.ncc_user}")
    private String pncc_user;

    @Override
    public void ykjovertimetoerp(){
        //获取友空间信息


        //调用友空间 查询人员信息  根据人员信息发送待办
        //接口授权的秘钥
        String token = SignHelper.getToken();
        //        if(StringUtils.isEmpty(token)) return new AjaxResult(300,"token验证失败,请联系管理员");
        String url = "https://c2.yonyoucloud.com/iuap-api-gateway/yonbip/uspace/openapi/iform/queryIFormDatas";
        url = url+ "?access_token="+token;
        JSONObject paramj = new JSONObject();

        paramj.put("pkBo","6e31fc68dc114704bf46a57272ddc510");
        paramj.put("iformUserId","3583ebc7-02e4-47e8-bfc5-c374e3f010f3");
        paramj.put("start",0);
        paramj.put("size",1000);
        paramj.put("queryOperator","And");

        JSONObject paramj2 = new JSONObject();
        paramj2.put("includeSubForm",true);
        paramj2.put("includeRefData",true);
        paramj2.put("includeFormModel",false);
        paramj.put("paramMap",paramj2);
        JSONObject paramj3 = new JSONObject();
        paramj3.put("columnCode","zdsj_1754375980506265");
        paramj3.put("queryOperator","MoreAndEqual");
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.MONTH,-1);
        Date time = instance.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(time);

        paramj3.put("columnValue",format);
        JSONArray andQueryConditions = new JSONArray();
        andQueryConditions.add(paramj3);
        paramj.put("andQueryConditions",andQueryConditions);

        String s = paramj.toString();
        logger.info("加班申请请求友空间表单数据查询入参: "+s);
        String s1 = OkHttpUtils.okHttpPost(url, s);
        logger.info("加班申请请求友空间表单数据查询返参: "+s1);
        //根据友空间信息整理
        JSONObject jsonObject = JSONObject.fromObject(s1);
        String s2 = jsonObject.optString("code");
        if("200".equals(s2)){
            JSONObject jsonObject1 = jsonObject.optJSONObject("data");
            JSONArray jsonArray = jsonObject1.optJSONArray("data");
            for (Object p : jsonArray) {
                JSONObject jsonObject2 = JSONObject.fromObject(p);
                //制单人编码
                String usercode = jsonObject2.optString("rybm_1754380037450173");
                //制单时间
                String s7 = jsonObject2.optString("zdsj_1754375980506265");
                //最后审批人
                String s10 = jsonObject2.optString("spyj_1755161623162144");
                String s12 = "";
                if(StringUtils.isNotBlank(s10)){
                    String[] s11 = s10.split("\\$");
                    s12 = s11[2].replace(" ","");
                }else{
                    s12 = "吴金晓";
                }


                //单据编码
                String s8 = jsonObject2.optString("NO_1754375980506810");
                JSONArray jsonArray1 = jsonObject2.optJSONArray("370b62e06b524dda807fe8e9e47b47ad");
                for (Object p2 : jsonArray1) {
                    JSONObject jsonObject3 = JSONObject.fromObject(p2);
                    //加班说明
                    String s3 = jsonObject3.optString("jbnr_1754377048745415");
                    //加班人员编码
                    String s4 = jsonObject3.optString("jbrybm_1754380312785375");
                    //加班时间
                    String s6 = jsonObject3.optString("rqqj_1754376825635118");
                    String[] split = s6.split(",");
                    String overtimes = split[0]+":00";
                    String overtimee = split[1]+":00";
                    String substring = overtimes.substring(0, 10);
                    String substring1 = overtimee.substring(0, 10);
                    //唯一pk
                    String s9 = jsonObject3.optString("pk");
                    OverTimePer overTimePer = new OverTimePer();
                    overTimePer.setSjid(s9);
                    List<OverTimePer> overTimePers = overTimeMapper.selectsjidList(overTimePer);
                    if (overTimePers.isEmpty()){

                        Date date = new Date();
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format1 = sdf2.format(date);

                        OverTimePer overTimePer2 = new OverTimePer();
                        overTimePer2.setCode(s4);
                        List<OverTimePer> overTimePers1 = overTimeMapper.selectOverTimePerList(overTimePer2);
                        OverTimePer overTimePer1 = overTimePers1.get(0);
                        OverTimePer zdr = new OverTimePer();
                        zdr.setCode(usercode);
                        List<OverTimePer> overTimePers2 = overTimeMapper.selectOverTimePerList(zdr);
                        OverTimePer overTimePer3 = overTimePers2.get(0);
                        //整理请求参数
                        JSONObject paramsp = new JSONObject();
                        //单据类型
                        paramsp.put("billType","6QJB");
                        //单据号
                        paramsp.put("billno",s8+s4);
                        //所属集团
                        paramsp.put("tenantId",overTimePer1.getPk_group());
                        //制单人编码
                        paramsp.put("usercode",usercode);
                        //类型
                        paramsp.put("type","HR");
                        //
                        paramsp.put("isCommit",false);
                        //制单人pk
                        paramsp.put("userId",overTimePer3.getPk_psndoc());
                        //员工pk
                        paramsp.put("staffId",overTimePer1.getPk_psndoc());
                        //状态
                        paramsp.put("status",2);
                        //所属集团
                        paramsp.put("pk_group",overTimePer1.getPk_group());
                        //加班结束时间
                        paramsp.put("overtimeendtime",overtimee);
                        //审批人pk
                        OverTimePer overTimePer4 = new OverTimePer();
                        overTimePer4.setName(s12);
                        List<OverTimePer> overTimePers3 = overTimeMapper.selectOverTimePerList(overTimePer4);
                        OverTimePer overTimePer5 = overTimePers3.get(0);
                        paramsp.put("approver",overTimePer5.getPk_psndoc());
                        //创建人pk
                        paramsp.put("creator",overTimePer3.getPk_psndoc());
                        //审批状态
                        // 0=审批未通过;
                        //1=审批通过;
                        //2=审批进行中;
                        //3=提交;
                        //-1=自由;
                        paramsp.put("approvestatus","1");
                        //备注
                        paramsp.put("remark",s3);
                        //审批时间
                        paramsp.put("approvetime",format1);
                        //组织
                        paramsp.put("pk_org",overTimePer1.getPk_org());
                        //是否跨天 布尔类型
                        if(substring.equals(substring1)){
                            paramsp.put("isoverday",false);
                        }else{
                            paramsp.put("isoverday",true);
                        }

                        //申请时间
                        paramsp.put("applydate",format1);
                        //申请人pk
                        paramsp.put("pk_psndoc",overTimePer1.getPk_psndoc());
                        //单据类型
                        paramsp.put("billtype","6QJB");
                        //制单人pk
                        paramsp.put("billmaker",overTimePer3.getPk_psndoc());
                        //是否通宵 布尔
                        paramsp.put("isallnight",false);
                        //创建时间
                        paramsp.put("creationtime",format1);
                        //单据来源
                        // 0=申请单;
                        //1=自动生成;
                        //2=手工录入;
                        paramsp.put("billsource","2");
                        //加班开始时间
                        paramsp.put("overtimebegintime",overtimes);
                        //先查询是否有 没有则进行查询

                        //推送
                        String pushtoerp = pushtoerp(paramsp.toString());
                        try{
                            JSONObject jsonObject4 = JSONObject.fromObject(pushtoerp);
                            String s5 = jsonObject4.optString("code");
                            if("200".equals(s5)){
                                overTimeMapper.insertsjid(overTimePer);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }


//                        overTimePer.setSjid(s8+s4);
//                        List<OverTimePer> overTimePers4 = overTimeMapper.selectsjidList(overTimePer);
//                        if(overTimePers4.isEmpty()){
//
//                        }

                    }

                }
            }
        }
    }

    public String pushtoerp(String param){

        IAPIUtils util = null;

        util = APIUtilsFactory.getAPIUtils(NCCVersionEnum.NCC2111);
        // 服务地址ip

        String ip = pip;
        String port = pport;

        // 账套编码，开发环境使用develop，生产环境需要使用用root账号登录，在“系统管理”节点查看账套编码
        String busi_center = pbusi_center;
        // 第三方应用编码

        String app_id = papp_id;

        String app_secret = papp_secret;

        // 公钥，加解密使用
        String public_key = ppublic_key;
        // ncc用户名
        String ncc_user = pncc_user;
        // ncc用户密码
        String password = "";
        // 公有云租户id
        String tenant_id = null;
        // 加密等级
        String secret_level = "L0";
        // 授权模式，客户端模式为client，密码模式为：password
        String grant_type = "client";
        util.init(ip, port, busi_center, app_id, app_secret, public_key, ncc_user, password);
        String token = null;
        try {
            token = util.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("获取token"+token);
        // 请求的OpenAPI接口地址，注意nccloud前面没有"/ nccloud/api/nccloud/api/uapbd/psndocmanage/psndoc/add"
        String apiuri = "nccloud/api/hrkq/hrentryapplyljj/savehrentryapply";
        util.setApiUrl(apiuri);
        // 对应接口地址的请求参数
        // 携带token访问接口，获取结果
        logger.info("请求erp加班新增接口入参: "+param);
        // 携带token访问接口，获取结果
        String result = null;
        try {
            result = util.getAPIRetrun(token, param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("请求erp加班新增接口返回参数: "+result);
        return result;
    }


}